"""
简化密码安全模块
使用 SHA256 加盐哈希，避免 bcrypt 的兼容性问题
"""

import hashlib
import secrets
import string

def generate_salt(length=16):
    """生成随机盐值"""
    alphabet = string.ascii_letters + string.digits
    return ''.join(secrets.choice(alphabet) for _ in range(length))

def get_password_hash(password: str) -> str:
    """获取密码哈希值"""
    salt = generate_salt()
    # 使用 SHA256 加盐哈希
    hash_obj = hashlib.sha256()
    hash_obj.update(password.encode('utf-8'))
    hash_obj.update(salt.encode('utf-8'))
    password_hash = hash_obj.hexdigest()
    
    # 返回格式: sha256$salt$hash
    return f"sha256${salt}${password_hash}"

def verify_password(plain_password: str, hashed_password: str) -> bool:
    """验证密码"""
    if not hashed_password.startswith('sha256$'):
        return False
    
    try:
        # 解析哈希值: sha256$salt$hash
        parts = hashed_password.split('$')
        if len(parts) != 3:
            return False
            
        salt = parts[1]
        expected_hash = parts[2]
        
        # 计算实际哈希值
        hash_obj = hashlib.sha256()
        hash_obj.update(plain_password.encode('utf-8'))
        hash_obj.update(salt.encode('utf-8'))
        actual_hash = hash_obj.hexdigest()
        
        return actual_hash == expected_hash
    except Exception:
        return False
